<?php

namespace app\admin\controller;

use app\common\BaseHelper as Helper;
use app\common\Common;

use app\admin\model\Image;
use app\admin\model\Fertilizertype;

use think\Request;

class Fertilizer extends Base
{
    public function _initialize() {
        parent::_initialize();

        $typeId = $this->request->param('typeId');
        $defaultWhere = [];
        $defaultWhere['typeId'] = $typeId;
        $this->defaultWhere = $defaultWhere;
        $this->searchFields = [
            'name' => [
                'label'     => '名称',
                'field'     => 'name',
                'type'      => 'text',
                'disabled'  => false,
                'condition' => 'like'
            ],
        ];

        $this->assign('typeId', $typeId);
        $typeName = Fertilizertype::where('id', $typeId)->value('name');
        $this->assign('typeName', $typeName);
    }

    public function index(){
        // 品类
        $typeList = Fertilizertype::order('sorting ASC')->select();
        $this->assign('typeList', $typeList);

        return parent::index();
    }

    public function add(Request $request) {

        return parent::add($request);
    }

    public function addPost(Request $request, $redirect = '') {
        $redirect = url('admin/fertilizer/index', ['typeId' => $request->param('typeId')]);

        return parent::addPost($request, $redirect);
    }

    public function edit(Request $request) {

        return parent::edit($request);
    }

    public function editPost(Request $request, $redirect = ''){
        $redirect = url('admin/fertilizer/index', ['typeId' => $request->param('typeId')]);

        return parent::editPost($request, $redirect);
    }

    public function delete() {

        return parent::delete();
    }

    /**
     * 将肥料移至另一品类
     */
    public function move() {
        $request = $this->request;
        if($request->isAjax()){
            $param = $request->param();
            $model = model($this->model);

            $ids = (Array)$param['ids'];
            foreach ($ids as $id) {
                $result = $model->where('id', $id)->update(['typeId' => $param['typeId']]);
            }

            if($result !== false) {
                return $this->success('移动成功！');
            } else {
                return $this->error('移动失败！');
            }
        }
    }

    /**
     * 筛选条件
     */
    public function getFilterWhere($request){
        $param = $request->param();
        $where = [];
        if($param['search']['value']) {
            $filter = json_decode($param['search']['value'],true);

            if(isset($filter['typeId']) && $filter['typeId']){
                $where['typeId'] = $filter['typeId'];
            }
            if(isset($filter['name']) && $filter['name']){
                $where['name'] = ['like', '%'.$filter['name'].'%'];
            }
        }

        return $where;
    }

}
